package net.dgg.rz.common.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.service.ScGeneralService;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import net.dgg.rz.common.constant.ScProductConstant;
import net.dgg.rz.common.entity.Order;
import net.dgg.rz.common.entity.Product;
import net.dgg.rz.common.excption.CommonExcption;
import net.dgg.rz.common.systemRecord.entity.SystemRecord;
import net.dgg.rz.common.systemRecord.service.SystemRecordService;
import net.dgg.rz.common.utils.DateUtils;
import net.dgg.rz.common.utils.StringUtils;
import net.dgg.rz.common.utils.ValidateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.ParseException;
import java.util.*;

/**
 * 接口service
 * <p>@Package: net.dgg.rz.common.service</p>
 * <p>@Title：OrderApiService</p>
 * <p>@description:</p>
 * <p>@author liulei</p>
 * <p>@date 2018年8月31日</p>
 * <p>@Company dgg</p>
 */
@Service
public class OrderApiService {


    @Autowired
    private CmsService smsservice;

    @Autowired
    private OrderService orderservice;

    @Autowired
    private ProductService productservice;


    @Autowired
    private UserService userservice;
    @Autowired
    private CommonService commonService;

    /**
     * 注册接口
     */
    @Autowired
    private CommonMangerExtService commonMangerExtService;

    @Autowired
    private SystemRecordService systemRecordService;


    @Autowired
    private DesUtil desUtil;

    @Autowired
    private ScGeneralService scGeneralService;

/*    *//**
     * iboos插入资质生产接口
     *
     *//*
    @Transactional
    @SuppressWarnings({"unchecked", "rawtypes"})
    public String insertOrder(String zzOrderMap, String zzProductMapList)  {
        Long curentUserId = 1L;//当前登录用户id,超级管理员
        UserEntity userentity;//当前登录人
        Map curentDept;//当前登录人部门
        JSONObject orderObj = JSONObject.parseObject(zzOrderMap);
        if (StringUtils.isNotEmpty(orderObj.get("createrId"))){
            //传过来的创建者
            userentity = userservice.findUserById(Long.valueOf(orderObj.get("createrId").toString()));
            curentDept = this.commonMangerExtService.findOrg(userentity.getOrgId());
        }else {
            //超级管理员
            userentity = userservice.findUserById(curentUserId);
            curentDept = this.commonMangerExtService.findOrg(userentity.getOrgId());
        }
        Order order = orderservice.selectByOrderId(orderObj.get("orderId") == null ? null : orderObj.getLong("orderId"));
        if(null == order) {
        	order = new Order();
        	String customerPhone = "";
        	String contactPhone = "";
        	if(!StringUtils.isEmpty(orderObj.get("customerPhone"))) {
        		customerPhone = desUtil.encrypt(orderObj.get("customerPhone").toString());
        	}
        	if(!StringUtils.isEmpty(orderObj.get("contactPhone"))) {
        		contactPhone = desUtil.encrypt(orderObj.get("contactPhone").toString());
        	}
            //销售订单map
            order.setId(DggKeyWorker.nextId());//唯一主键
            order.setOrderId(orderObj.get("orderId") == null ? null : orderObj.getLong("orderId"));
            order.setOrderNo(orderObj.get("orderNo").toString());
            order.setScOrderNo(orderObj.get("scOrderNo").toString());
            order.setBusinessId(orderObj.get("businessId") == null ? null : orderObj.getLong("businessId"));
            order.setBusinessNo(orderObj.get("businessNo").toString());
            order.setCustomerId(orderObj.get("customerId") == null ? null : orderObj.getLong("customerId"));
            order.setCustomerNo(orderObj.get("customerNo").toString());
            order.setCustomerPhone(customerPhone);
            order.setCustomerName(orderObj.get("customerName") == null ? null : orderObj.getString("customerName"));
            order.setContactPhone(contactPhone);
            order.setBusinessTypeId(orderObj.get("businessTypeId") == null ? null : orderObj.getString("businessTypeId"));
            order.setBusinessTypeName(orderObj.get("businessTypeName") == null ? null : orderObj.getString("businessTypeName"));
            order.setSignUserId(orderObj.get("signUserId") == null ? null : orderObj.getLong("signUserId"));
            order.setSignUserName(orderObj.get("signUserName") == null ? null : orderObj.getString("signUserName"));
            Long signOrgId = orderObj.get("signOrgId") == null ? null : orderObj.getLong("signOrgId");
            if (null != signOrgId) {
                Map deptMap = this.commonMangerExtService.findOrg(signOrgId);
                if (null != deptMap) {
                    order.setSignUserOrgId(Long.parseLong(deptMap.get("id").toString()));
                    order.setSignUserOrgName(deptMap.get("name").toString());
                }
            }
            order.setSignOrgId(orderObj.get("sourceDeptId") == null ? null : orderObj.getLong("sourceDeptId"));
            order.setSignOrgName(orderObj.get("sourceDeptName") == null ? null : orderObj.getString("sourceDeptName"));
            order.setMoney(orderObj.get("money") == null ? null : orderObj.getBigDecimal("money"));
            order.setPayStatus(orderObj.get("payStatus") == null ? null : orderObj.getString("payStatus"));
            order.setPayMethod(orderObj.get("payMethod") == null ? null : orderObj.getString("payMethod"));
            order.setContractNo(orderObj.get("contractNo") == null ? null : orderObj.getString("contractNo"));
            order.setSignDate(orderObj.get("signDate") == null ? null : orderObj.getDate("signDate"));

            order.setCreaterId(userentity.getId());
            order.setCreaterName(userentity.getRealName());
            order.setCreateTime(new Date());
            order.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
            order.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            orderservice.ibossInsert(order);//插入销售订单
        }
        //销售子订单map
        // zzProductMapList = obj.get("gsscProductMapList").toString();////测试
        JSONArray productList = JSONObject.parseArray(zzProductMapList);
        for (int i = 0; i < productList.size(); i++) {
            String productString = productList.getString(i);
            JSONObject productObj = JSONObject.parseObject(productString);
            Product product = new Product();//销售产品子订单
            product.setId(DggKeyWorker.nextId());
            product.setOrderId(order.getOrderId());

            product.setOrderBusinessId(productObj.get("orderBusId") == null ? null : productObj.getLong("orderBusId"));
            product.setBusinessTypeId(productObj.get("businessTypeId") == null ? null : productObj.getString("businessTypeId"));
            product.setOrderBusinessNo(productObj.get("orderBusNo") == null ? null : productObj.getString("orderBusNo"));
            product.setBusinessTypeName(productObj.get("businessTypeName") == null ? null : productObj.getString("businessTypeName"));
            //这个关键字段必须要有值
            ValidateUtils.strNotEmpty(productObj.get("businessProductId"),CommonExcption.class,"该子订单没有业态CODE,无法下单!");
            product.setBusinessProductCode(productObj.getString("businessProductId"));
            product.setBusinessProductName(productObj.get("businessProductName") == null ? null : productObj.getString("businessProductName"));
            product.setProductId(productObj.get("productId") == null ? null : productObj.getLong("productId"));
            product.setProductName(productObj.get("productName") == null ? null : productObj.getString("productName"));
            product.setProductAttr(productObj.get("productAttr") == null ? null : productObj.getString("productAttr"));
            product.setServiceAreaId(productObj.get("serviceAreaId") == null ? null : productObj.getLong("serviceAreaId"));
            product.setServiceArea(productObj.get("serviceArea") == null ? null : productObj.getString("serviceArea"));

            product.setContractNo(productObj.get("contractNo") == null ? null : productObj.getString("contractNo"));
            product.setOrderTime(productObj.get("orderTime") == null ? null : productObj.getDate("orderTime"));
            product.setMoney(productObj.get("money") == null ? null : productObj.getBigDecimal("money"));
            product.setPayMethod(productObj.get("payMethod") == null ? null : productObj.getString("payMethod"));
            //这个证书用的费用状态写死
            product.setCostState("NOT_APPLAY");
            product.setProductOrgId(productObj.get("productOrgId") == null ? null : productObj.getLong("productOrgId"));
            product.setProductOrgName(productObj.get("productOrgName") == null ? null : productObj.getString("productOrgName"));

            product.setCreaterId(userentity.getId());
            product.setCreaterName(userentity.getRealName());
            product.setCreateTime(new Date());
            product.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
            product.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());

            //生产订单表
            ProductOrder productOrder = new ProductOrder();
            productOrder.setId(DggKeyWorker.nextId());
            String number = smsservice.getBillNumber("sc");
            if(StringUtils.isEmpty(number)){
                //return "单据号获取失败,请联系管理员";
             ValidateUtils.isTrue(StringUtils.isNotEmpty(number), CommonExcption.class, "单据号获取失败,请联系管理员");
            }
            productOrder.setScProductOrderNo(number);
            productOrder.setOrderId(order.getOrderId());
            productOrder.setOrderNo(order.getOrderNo());
            productOrder.setOrderBusId(productObj.get("orderBusId") == null ? null : productObj.getLong("orderBusId"));
            productOrder.setOrderBusNo(productObj.get("orderBusNo") == null ? null : productObj.getString("orderBusNo"));
            productOrder.setBusinessId(order.getBusinessId());
            productOrder.setBusinessNo(order.getBusinessNo());
            productOrder.setCustomerId(order.getCustomerId());
            productOrder.setCustomerNo(order.getCustomerNo());
            productOrder.setCustomerPhone(order.getCustomerPhone());
            productOrder.setCustomerName(order.getCustomerName());
            productOrder.setContactPbone(order.getContactPhone());
            productOrder.setProductOrgId(product.getProductOrgId());
            productOrder.setProductOrgName(product.getProductOrgName());
            productOrder.setBusinessTypeCode(product.getBusinessTypeId());
            productOrder.setBusinessTypeName(product.getBusinessTypeName());
            productOrder.setBusinessProductCode(product.getBusinessProductCode());
            productOrder.setBusinessProductName(product.getBusinessProductName());
            productOrder.setProductId(product.getProductId());
            productOrder.setProductName(product.getProductName());
            productOrder.setChannelId(productObj.get("channelId") == null ? null : productObj.getLong("channelId"));
            productOrder.setChannelName(productObj.get("channelName") == null ? null : productObj.getString("channelName"));
            productOrder.setContractNo(product.getContractNo());
            productOrder.setOrderTime(product.getOrderTime());
            productOrder.setMoney(product.getMoney());
            productOrder.setPayMethod(product.getPayMethod());
            productOrder.setSignUserId(order.getSignUserId());
            productOrder.setSignUserName(order.getSignUserName());
            productOrder.setContractNo(order.getContractNo());
            productOrder.setSignUserOrgId(order.getSignUserOrgId());
            productOrder.setSignUserOrgName(order.getSignUserOrgName());
            productOrder.setSignOrgId(order.getSignOrgId());
            productOrder.setSignOrgName(order.getSignOrgName());
            productOrder.setSignTime(order.getSignDate());///签单时间需要增加此字段
            productOrder.setStatus(ScProductConstant.SC_TO_RECEIVE_XDDJS);//下单待分配
            productOrder.setRemark(productObj.get("remark") == null ? null : productObj.getString("remark"));
            productOrder.setCreaterId(userentity.getId());
            productOrder.setCreaterName(userentity.getRealName());
            productOrder.setCreateTime(new Date());
            productOrder.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
            productOrder.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            productOrder.setSignTime(order.getSignDate());
            productOrder.setReceiveOrderDate(new Date());
            //插入流程id
            Map maps = new HashMap<>();
            maps.put("deptId", product.getProductOrgId());
            maps.put("businessCode", product.getBusinessProductCode());
            ProductNodeFlow node = nodeFlowDao.queryFlow(maps);
            ValidateUtils.isTrue(StringUtils.isNotEmpty(node), CommonExcption.class, "未查询到"+productOrder.getProductOrgName()+"["+productOrder.getBusinessProductName()+"]流程节点的配置信息");
    		  productOrder.setNodeFlowId(node.getId());
            productOrderDao.iboosInsertSelective(productOrder);
            
            product.setRelevanceCredential(0);
            product.setCostState(ScProductConstant.NOT_APPLAY);
            product.setScProductOrderId(productOrder.getId());
            product.setScProductOrderNo(productOrder.getScProductOrderNo());
            productservice.iboosInsertProduct(product);

            //插入操作记录
            SystemRecord record = new SystemRecord();
            record.setId(DggKeyWorker.nextId());//id
            record.setSource("3");
            record.setWorkTableName("rzsc_product_order");
            record.setWorkId(productOrder.getId());
            record.setWorkNo(productOrder.getScProductOrderNo());
            record.setBeOperaterId(curentUserId);
            record.setOperateType("1");
            record.setRemarks("新增生产订单");
            systemRecordService.apiSave(record, userentity);

            //生产订单超期
            ProductTimeStatus timestatus = new ProductTimeStatus();
            timestatus.setId(productOrder.getId());
            timestatus.setScProductOrderNo(productOrder.getScProductOrderNo());
            timestatus.setDistributionStartTime(new Date());//计时开始时间
            timestatus.setDistributionTimeOutStatus(ScProductConstant.NORMAL);
            timestatus.setFlag(1);//必须要加入
            timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);//写入节点超期状态,默认不超期
            timestatus.setOrderTimeStatus(ScProductConstant.NORMAL);
            timestatus.setCreaterId(userentity.getId());
            timestatus.setCreaterName(userentity.getRealName());
            timestatus.setCreateTime(new Date());
            timestatus.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
            timestatus.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            try {
                timestatus.setDistributionEndTime(DateUtils.dateAddDayJs(new Date(), 1));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(node.getIsnaturalorworkday()==1) {//工作日
                Date nowDate = new Date();
                String orderEndTime = smsservice.findAfterDate(DateUtil.dateToString(nowDate,"yyyy-MM-dd HH:mm:ss"),node.getManagementCycle())+" "+DateUtil.dateToString(nowDate,"HH:mm:ss");
                timestatus.setOrderEndTime(DateUtil.stringToDate(orderEndTime,"yyyy-MM-dd HH:mm:ss"));
            }else {
                try {
                    timestatus.setOrderEndTime(DateUtils.dateAddDayJs(new Date(), node.getManagementCycle()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            producttimestatusdao.iboosinsertSelective(timestatus);

            //插入生产订单数据
            ProductData data = new ProductData();
            data.setId(DggKeyWorker.nextId());
            data.setScProductId(productOrder.getId());
            data.setScProductNo(productOrder.getScProductOrderNo());
            data.setCreaterId(userentity.getId());
            data.setCreaterName(userentity.getRealName());
            data.setCreateTime(new Date());
            data.setCreaterOrgId(null == curentDept ? null : Long.parseLong(curentDept.get("id").toString()));
            data.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            productdatadao.ibossInsertSelective(data);
            // 同步订单信息到生产主订单库
            Map scOrderMap = new HashMap();
            scOrderMap.put("scOrderId", productOrder.getId());
            scOrderMap.put("scOrderNo", productOrder.getScProductOrderNo());
            scOrderMap.put("orderId", order.getOrderId());
            scOrderMap.put("orderNo", order.getOrderNo());
            scOrderMap.put("businessId", order.getBusinessId());
            scOrderMap.put("businessNo", order.getBusinessNo());
            scOrderMap.put("customerId", order.getCustomerId());
            scOrderMap.put("customerNo", order.getCustomerNo());
            scOrderMap.put("customerPhone", order.getCustomerPhone());
            scOrderMap.put("customerName", order.getCustomerName());
            scOrderMap.put("belongScSystem", "SC_ZZSC");//资质生产标识
            try {
                scGeneralService.synchronizationScorder(scOrderMap);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CommonExcption("数据同步到通用版系统出现错误！");
            }
            try {//发送失败就算了
                if ("BUS_YT_ZZ_ZS".equals(productOrder.getBusinessProductCode())){
                    String[] msgs = new String[]{DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
                    List<UserEntity> users;
                    String[] codes = new String[]{"ZZSC_ZS_ADMIN", "ZZSC_ZS_SUPER_ADMIN"};
                    users = userservice.findUserByRoleCodesAndOrgs(codes, 0, product.getProductOrgId());
                    if (users == null){
                        users = new ArrayList<>();
                    }
                    commonService.sendMsgByAsynchronous(users,msgs,"ZZSC_SC_NEW_SZ");//收证入库新增消息
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "success";
    }*/
}

